import React, {useState, useEffect, useRef} from 'react'
import { View, Input } from '@tarojs/components'
import Taro, {useRouter} from '@tarojs/taro'
import CommentsList from '../../components/CommentsList'
import './index.scss'
import {RouterProps, CommentProps} from '../tieDetail/index'

interface ResultProps {
  errCode: string;
  errMsg: string;
  data: CommentProps[];
}

interface ResProps extends Taro.cloud.CallFunctionResult {
  result: ResultProps;
  [key: string]: any;
}

export default function tieComments() {
  const [publishComments, setPublishComments] = useState('')
  const [tieziId, setTieziId] = useState('')
  const [comments, setComments] = useState<CommentProps[]>([])
  const myInput = useRef<HTMLInputElement>(null)
  const router = useRouter<RouterProps>()

  useEffect(() => {
    console.log('路由：', router)
    setTieziId(router.params.id)

    getTieCommentsData(router.params.id)
  }, [])

  // 请求帖子评论数据
  function getTieCommentsData(id) {
    Taro.cloud.callFunction({
      name: 'tiezi',
      data: {
        type: 'getTieComments',
        id
      }
    })
    .then((res: ResProps) => {
      console.log('获取帖子数据：', res.result)
      setComments(res.result.data)
    })
    .catch(err => {
      console.log('获取帖子数据失败：', err)
    })
  }

  // 输入框焦点事件
  function getInputFocus() {
    myInput && myInput.current && myInput.current.focus()
  }

  const handlePublishCommentsChange = (e) => {
    console.log('评论内容：', e)
    setPublishComments(e.target.value)
  }

  // 提交回复/评论
  const submitReply = () => {
    Taro.cloud.callFunction({
      name: 'tiezi',
      data: {
        type: 'addComment',
        tieziId,
        content: publishComments,
        userId: '当前评论人',
        comment_id: 'bf4a0bf261e7b14507a394cb01790f31'
      }
    })
    .then(res => {
      console.log('评论成功：', res.result)
    })
    .catch(err => {
      console.log('评论失败：', err)
    })
  }

  return (
    <View className='tie-comments'>
      <CommentsList setComment={getInputFocus} />

      {/* 发表评论 */}
      <View className='tiezi-publish'>
        <Input
          className='tiezi-publish-input'
          placeholder='说说您的看法'
          value={publishComments}
          onInput={handlePublishCommentsChange}
          onConfirm={submitReply}
          ref={myInput}
        />
      </View>
    </View>
  )
}
